package xyz.penghaonan.adtools.adview;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import xyz.penghaonan.adtools.ADLog;
import xyz.penghaonan.adtools.ADTools;
import xyz.penghaonan.adtools.R;
import xyz.penghaonan.adtools.manager.AdSpotInfo;

public abstract class BaseAdView extends FrameLayout {

    private long viewId;
    private AdSpotInfo adSpotInfo;

    public BaseAdView(@NonNull Context context) {
        super(context);
        preInit(null);
    }

    public BaseAdView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        preInit(attrs);
    }

    public BaseAdView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        preInit(attrs);
    }

    private void preInit(AttributeSet attrs) {
        viewId = System.currentTimeMillis();
        if (!ADTools.isEnable()) {
            return;
        }
        if (attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.BaseAdView);
            String spotId = a.getString(R.styleable.BaseAdView_spot_id);
            adSpotInfo = ADTools.findSpotInfo(spotId);
            a.recycle();
        }
        init(attrs);
    }

    abstract String adViewType();

    abstract void init(AttributeSet attrs);

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (adSpotInfo == null) {
            return;
        }
        ADLog.i("(" + adSpotInfo.spotId + ")" + "onAttachedToWindow");
        ADTools.requestAdBanner(getContext(), adSpotInfo.spotId, new ADTools.AdViewCallback() {
            @Override
            public void onAdViewCallback(View adView) {
                addView(adView);
            }

            @Override
            public void onAdViewLoadFailed(String msg) {

            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (adSpotInfo == null) {
            return;
        }
        ADLog.i("(" + adSpotInfo.spotId + ")" + "onDetachedFromWindow");
        ADTools.cancelRequest(adSpotInfo.spotId);
    }
}
